import 'dart:convert';
import 'dart:io';

import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:package_info/package_info.dart';
import 'package:tender_flutter/generated/json/base/json_convert_content.dart';
import 'package:tender_flutter/page/home/model/app_version_entity.dart';

class AppUpdateUtils {
  AppUpdateUtils._internal();

  static void init() {
    if (Platform.isAndroid) {
      FlutterXUpdate.init(

              ///是否输出日志
              debug: true,

              ///是否使用post请求
              isPost: false,

              ///post请求是否是上传json
              isPostJson: false,

              ///请求响应超时时间
              timeout: 25000,

              ///是否开启自动模式
              isWifiOnly: false,

              ///是否开启自动模式
              isAutoMode: false,

              ///需要设置的公共参数
              supportSilentInstall: false,

              ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
              enableRetry: false)
          .then((value) {})
          .catchError((error) {
        print(error);
      });

      /// 自定义JSON
      FlutterXUpdate.setCustomParseHandler(onUpdateParse: (String json) async {
        Map<dynamic, dynamic> map = jsonDecode(json);
        AppVersionEntity entity =
            JsonConvert.fromJsonAsT<AppVersionEntity>(map);
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        String buildNumber = packageInfo.buildNumber;
        return UpdateEntity(
            hasUpdate:
                entity.data.versionCode > int.parse(buildNumber) ? true : false,
            versionCode: entity.data.versionCode,
            versionName: entity.data.versionName,
            updateContent: entity.data.updateContent,
            downloadUrl: entity.data.url);
      });

      FlutterXUpdate.setErrorHandler(
          onUpdateError: (Map<String, dynamic> message) async {
        print(message);
      });
    } else {
      print("ios暂不支持XUpdate更新");
    }
  }
}
